package org.example.route.service.impl;

import jakarta.servlet.http.HttpServletResponse;
import org.example.route.constant.PriceConstant;
import org.example.route.constant.TrainConstant;
import org.example.route.handler.ExcelHandler;
import org.example.route.handler.RouteExcelHandler;
import org.example.route.mapper.*;
import org.example.route.model.dto.BaseRequest;
import org.example.route.model.dto.PriceDTO;
import org.example.route.model.dto.PriceQueryDTO;
import org.example.route.model.pojo.Order;
import org.example.route.model.pojo.Price;
import org.example.route.model.pojo.Station;
import org.example.route.model.pojo.StationRoute;
import org.example.route.model.vo.PriceVO;
import org.example.route.service.PriceService;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/*
* public class PriceQueryDTO {
   private Long cityId1;
   private Long cityId2;
   private Long trainKind;//车的种类
   private LocalDateTime startTime;//出发的日期
   private Long grade;
   private Long count;
   private Long stationId1;
   private Long stationId2;
}
* */

@Service
public class PriceServiceImpl implements PriceService {
    @Autowired
    private PriceMapper priceMapper;
    @Autowired
    private StationMapper stationMapper;
    @Autowired
    private StationRouteMapper stationRouteMapper;
    @Autowired
    private TrainMapper trainMapper;
    @Autowired
    private OrderMapper orderMapper;

    DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @Override
    public void add(PriceDTO priceDTO) {
        priceMapper.add(priceDTO);
    }


    //后台信息管理价格，而不是买者的查询
    //目前只能查询一条路线上的车位
    @Override
    @Transactional
    public List<PriceVO> list(PriceQueryDTO priceQueryDTO) {

        //查对应的站点起始站
        List<Station> stations1 = stationMapper.getByCityId(priceQueryDTO.getCityId1());

        //查对应的站点到达站
        List<Station> stations2 = stationMapper.getByCityId(priceQueryDTO.getCityId2());

        //获得所有起始站点
        List<StationRoute> stationRoutesStart = new ArrayList<>();

        //获得所有到达站点
        List<StationRoute> stationRoutesTarget = new ArrayList<>();

        List<PriceVO> priceVOs = new ArrayList<>();

        //前端未给出起始站的代码
        if(priceQueryDTO.getStationId1() == null) {
           for (Station station1 : stations1)
           {
               priceQueryDTO.setStationId1(station1.getId());

               List<StationRoute> stationRoutesStart1 = stationRouteMapper.getStartByPriceDTO(priceQueryDTO);

               stationRoutesStart.addAll(stationRoutesStart1);

           }
        }else {
            List<StationRoute> stationRoutesStart1 = stationRouteMapper.getStartByPriceDTO(priceQueryDTO);

            stationRoutesStart.addAll(stationRoutesStart1);
        }

        if(priceQueryDTO.getStationId2() == null)
        {
            for (Station station2 : stations2)
            {
                priceQueryDTO.setStationId2(station2.getId());
                List<StationRoute> stationRoutesTarget1 = stationRouteMapper.getTargetByPriceDTO(priceQueryDTO);
                stationRoutesTarget.addAll(stationRoutesTarget1);
            }

        }else{
            List<StationRoute> stationRoutesTarget1 = stationRouteMapper.getTargetByPriceDTO(priceQueryDTO);
            stationRoutesTarget.addAll(stationRoutesTarget1);
        }


        //整理所有的起始点和目标点，找到可以连成一条线的路线
        for (StationRoute stationRouteStart : stationRoutesStart)
            for (StationRoute stationRouteTarget : stationRoutesTarget)
            {
               if (stationRouteStart.getRouteId().equals(stationRouteTarget.getRouteId()) && stationRouteStart.getTrainId().equals(stationRouteTarget.getTrainId())
                 && stationRouteStart.getSequence() < stationRouteTarget.getSequence()
               ){
                   //表示成立
                   List<Price> prices = priceMapper.getByDoubleIdsAndGrade(stationRouteStart.getId(), stationRouteTarget.getId(), priceQueryDTO.getGrade());
                   System.out.println("=========================================" + prices);
                   LocalDateTime endTime = stationRouteTarget.getGoTime();
                   LocalDateTime startTime = stationRouteStart.getArrivalTime();
                   String goName1 = stationMapper.getNameById(stationRouteStart.getStationId());
                   String goName2 = stationMapper.getNameById(stationRouteTarget.getStationId());


                   Long trainId = stationRouteStart.getTrainId();
                   Long kind = trainMapper.getKindById(trainId);
                   String kindName = kind.equals(TrainConstant.KIND_ORDINARY) ? "普通车" : kind.equals(TrainConstant.KIND_HIGH_SPEED) ? "高铁" : "动车";
                   String trainSerialNumber = trainMapper.getSerialById(trainId);
                   if(!prices.isEmpty()) {



                       for (Price price : prices) {
                           PriceVO priceVO = new PriceVO();
                           BeanUtils.copyProperties(price, priceVO);
                           priceVO.setGoName1(goName1);
                           priceVO.setGoName2(goName2);
                           priceVO.setGradeName(gainGradeName(price.getGrade(),trainId));
                           priceVO.setEndTime(sdf.format(endTime));
                           priceVO.setStartTime(sdf.format(startTime));
                           priceVO.setTrainId(trainId);
                           priceVO.setTrainSerialNumber(trainSerialNumber);
                           priceVO.setKind(kind);
                           priceVO.setKindName(kindName);
                           priceVOs.add(priceVO);

                       }
                   }

               }
            }




   return priceVOs;

    }

    /**
     *
     * 根据等级获得对应的Name
     *
     * **/
    private String gainGradeName(Long grade,Long trainId) {

        if (trainMapper.getKindById(trainId).equals(TrainConstant.KIND_ORDINARY)) {
           return grade.equals(PriceConstant.GRADE_HIGH) ? "软卧" : grade.equals(PriceConstant.GRADE_MIDDLE) ? "硬卧" : "硬座";
        } else {
            return grade.equals(PriceConstant.GRADE_HIGH) ? "商务座" : grade.equals(PriceConstant.GRADE_MIDDLE) ? "一等座" : " 二等座";
        }
    }

    //TODO 等一辆高铁完成了它的时间，（或者一天）（可以是走完全程，可以是走到某一站，看想要什么样的难度）那么就可以将相关的
    //TODO 座位全部清空，将相关的价格也删掉，路线也要删掉
    //TODO 或者说不删路线


    public void deleteTimeArrived()
    {

    }


    //删除价格信息
    @Override
    public void delete(BaseRequest baseRequest) {
        Price price = priceMapper.getById(Long.parseLong(baseRequest.getKey()));
        if (Objects.isNull(price))
        {
            throw new RuntimeException("价格不存在");
        }

        //查询订单中是否有
        List<Order> orders = orderMapper.listByPriceId(price.getId());
        if (!orders.isEmpty()){
            throw new RuntimeException("价格被订单占用，请先删除订单");
        }

        priceMapper.delete(price.getId());


    }

    @Override
    @Transactional
    public void generateTable(PriceQueryDTO priceQueryDTO, HttpServletResponse response) {
        try {
            List<PriceVO> priceVOs = list(priceQueryDTO);
            ExcelHandler excelHandler = new RouteExcelHandler();
            excelHandler.fileDownload(priceVOs, "列车运行时间表", response);
        } catch (Exception e) {
            // 记录日志或返回错误信息
            throw new RuntimeException("生成表格失败: " + e.getMessage(), e);
        }
    }

    /**
     *
     * AI方法
     *
     * **/
    //TODO
    @Tool(description = "生成关于价格和路线的表格，在浏览器中下载")
    public void generateTableAI(){



    }

    @Override
    public void update(PriceDTO priceDTO) {
        List<Order> orders = orderMapper.listByPriceId(priceDTO.getId());
        if (!orders.isEmpty()){
            throw new RuntimeException("价格被订单占用，请先删除订单");
        }

        priceMapper.update(priceDTO);
    }
}
